package cn.melonlib.cores.aop.comp.inject;

import cn.hutool.core.bean.BeanUtil;
import cn.melonlib.cores.commons.comp.utils.AdvancedStringUtils;
import cn.melonlib.cores.identification.comp.messenger.IdentificationMessenger;
import cn.melonlib.cores.identification.model.entity.Organization;
import cn.melonlib.cores.jpa.model.bean.collections.JsonMap;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.hibernate.service.spi.ServiceException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Map;

@Component
public class FilterTenantInterceptor extends ApplicationObjectSupport implements MethodInterceptor {


    @Nullable
    @Override
    public Object invoke(@NotNull MethodInvocation methodInvocation) throws Throwable {
        IdentificationMessenger identificationMessenger=this.getApplicationContext().getBean(IdentificationMessenger.class);
        Arrays.stream(methodInvocation.getArguments()).forEach(arg->{
            try {
                Organization organization = identificationMessenger.getOrganization();
                String code = AdvancedStringUtils.defaultIfBlank(BeanUtil.getProperty(organization, "code")
                        ,()->BeanUtil.getProperty(organization, "domain"));
                if (arg instanceof Map) {
                    ((Map<String, Object>) arg).put("tenantCode", JsonMap.createMap().append("eq", code));
                }
            }catch (Exception e){
                throw new ServiceException(e.getMessage(),e);
            }
        });
        return methodInvocation.proceed();
    }
}
